<!-- 生产执行->工序汇报单 -->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper" style="display:block">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <btns-wrapper @searchClick="searchClick" :showModel="showModel" :orderId="orderId" :voucherState="voucherState" :editMask="editMask" @printOrder="printOrder" @switchList="switchList" @submitServer="submitServer" @clickEdit="clickEdit" @deleteOrder="deleteOrder" @getIdByData="getIdByData" @auditClick="auditClick" @turnThePage="turnThePage" @syncOrder="syncOrder" @submitOrder="submitOrder" @exportDetail="exportDetail" :sourceCode="sourceCode">
                    <template slot="neworder">
                        <a-dropdown class="btns" key="new" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增
                                    <a-icon type="down" style="color:rgb(24,144,255);vertical-align:middle;" />
                                </div>
                            </a>
                            <a-menu slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="newForecast">新增</a>
                                </a-menu-item>
                                <a-menu-item key="1">
                                    <a href="javascript:void(0)" @click="choiceProduct">选单</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template>
                    <!-- <template slot="shengdan">
                        <a-dropdown class="btns" key="sheng" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="snippets" />
                                <div class="btns-text">生单
                                    <a-icon type="down" />
                                </div>
                            </a>
                            <a-menu v-if="voucherState==1" slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="generateBills('ProductReceiveVoucher')">生成成品入库单</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template> -->
                </btns-wrapper>
            </div>
            <div ref="print" class="documents-wrapper" id="documents-wrapper">
                <h3 class="text-center">
                    {{voucherTitle}}
                </h3>
                <section v-show="showModel=='list'">
                    <!--列表-->
                    <dynamicList ref="dyList" :basePostData="basePostData" :sourceCode="sourceCode" @switchList="switchList" @dblclick="getIdByData" :reportCode="reportCodeList"></dynamicList>
                </section>
                <section v-show="showModel=='order'">
                    <div><span class="audit-status" v-show="voucherState==0">待审核</span><span class="audit-status" v-show="voucherState==1 || voucherState==10">{{voucherState==1?'已审核':'关闭'}}</span></div>
                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <order-dynamic-form v-if="isHeaderShow" :FormData="orderHeaderData" @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-header" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="table-box">
                            <a-table id="bills_tb" :columns="columns" :data-source="dataSource" :customRow="customClick" :scroll="{ x: 1000, y: 347 }" :pagination="false" @change="onTableChange" :size="small" bordered>
                                <template slot="number" v-if="isRouterAlive" slot-scope="text, record, index">

                                    <div v-if="index == dataSource.length-1">
                                        合计
                                    </div>
                                    <div v-else>
                                        {{index+1}}
                                    </div>
                                </template>
                                <template v-for="col in slotArray" :slot="col" slot-scope="text, record,index">
                                    <div data-key="">
                                        <editable-cell v-if="isRouterAlive" :checkType="checkType" :text="text" :col="col" :index="index" :record="record" :dataSource="dataSource" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap"  @choiceAddData="choiceAddData(index,col,$event)" @change="onCellChange(index, col, $event)" @newAddData="handleAdd" />
                                    </div>
                                </template>
                            </a-table>
                            <div class="edit-mask" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="footer-box">
                            <order-dynamic-form v-if="isHeaderShow" :FormData="orderFooterData"></order-dynamic-form>
                            <div class="edit-mask-footer" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                    </a-form-model>

                </section>
                <section v-show="showModel=='detail'">
                    <!--明细-->
                    <dynamicListDetails ref="detailSearchRef" :reportCode="reportCodeDetail" :componentType="1" :basePostData="basePostData"></dynamicListDetails>
                </section>
                <section v-show="showModel=='statistical'">
                    <!--统计-->
                    <dynamicListDetails ref="statisticalSearchRef" :reportCode="reportCodeStatistical" :componentType="2" :basePostData="basePostData"></dynamicListDetails>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
            <drawerBox ref="searchList" :unitData="unitData" :unitsData="unitsData" :unitsDataDetails="unitsDataDetails" @editClickOrder="editClickOrder"></drawerBox>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>
        <!--分单-->
        <production-in-modal ref="productionInRef"></production-in-modal>

        <!-- 选生产任务单 -->
        <a-modal title="选择生产产品" :visible="visibleProcessing" centered width="1100px" @cancel="cancelProcessing">
            <template>
                <!-- <p>选择加工产品</p> -->
                <div style="min-height: 230px;">
                    <!-- :rowClassName="rowClassMax" -->
                    <a-table :scroll="{ x: 1000, y: 200 }" :columns="columnCheckMax" :data-source="columnCheckMaxData" bordered :pagination="false" :row-selection="{ selectedRowKeys: selectedRowMaxKeys, onChange: onSelectChangeMax,columnsWidth:20 }"></a-table>
                </div>
                <div class="titleDiv">
                    <div>汇报日期:{{dayDate}}</div>
                    <div class="title">工序汇报</div>
                </div>
                <div class="table-box-mmp" style="min-height: 230px;">
                    <a-table :scroll="{ x: 1000, y: 200 }" :columns="columnCheckMin" :data-source="columnCheckMinData" bordered :pagination="false" :row-selection="{ selectedRowKeys: selectedRowMinKeys, onChange: onSelectChangeMin,columnsWidth:40 }">
                        <template v-for="col in slotArry" :slot="col" slot-scope="text, record, index">
                            <div data-key="">
                                <editableCells v-if="isRouterAlive" :dynamicAllData="timeSlotArr" :showTotal="false" :text="text" :col="col" :index="index" :record="record" @change="onCellChange(index, col, $event)" :dataSource="modalList2" />
                            </div>
                        </template>
                    </a-table>
                </div>
            </template>
            <template slot="footer">
                <div>
                    <a-button type="primary" @click="addClick">确定</a-button>
                    <a-button @click="cancelProcessing()" class="margin-left-10">关闭</a-button>
                </div>
            </template>
            <div class="contextmenu-box" ref="contextmenuBox">
                <!-- 右键菜单 -->
                <ul v-show="visible" class="contextmenu">
                    <li @click="handleDelete()">删除行</li>
                </ul>
            </div>
        </a-modal>
    </div>
</template>
<script>


import { saveReport, exameReport, deleteReport, getCodeReport, submitOrder, getUnFinishProductionWorkVo } from '@/api/production/productionProcessReport';
import { listProcessRouteAndPriceDetailVoByRouteDetailIds } from '@/api/production/processRoute';

import pro from '@/mixins/procurement/pro'
import getDate from "@/utils/tool/date";
import productionInModal from '@/components/SeparateBill/productionInModal.vue';

export default {
    components: { productionInModal },
    mixins: [pro],
    data () {
        return {
            basePostData: {
                someBusinessType: null,    // 指定业务类型 默认 0
            },
            sourceCode: 'ProductionWorkReport',
            reportCodeDetail: 'ProductionWorkReport_Detail_Report',          //明细code
            reportCodeStatistical: 'ProductionWorkReport_Statistic_Report',   //统计code
            reportCodeList: 'ProductionWorkReport_List_Report',              //列表code
            receiveDeliverType: 1,//1入，2出

            //隐藏明细当中的仓库和仓库编码
            isHideWherehouse: false,
            checkType: 'is_made_self',//自制
            isHeaderShow: true,                 //是否显示 表头表尾



            visibleProcessing: false,
            maxClickId: null,
            columnCheckMax: [
                {
                    title: "生产车间",
                    dataIndex: "officeName",
                    align: 'center',
                    width: 80
                },
                {
                    title: "生产单号",
                    dataIndex: "productionWorkCode",
                    align: 'center',
                    width: 80
                },
                // {
                //   title: "物料编码",
                //   dataIndex: "inventoryCode",
                //   align: 'center',
                //   scopedSlots: {
                //     customRender: "inventoryCode",
                //   },
                // },
                {
                    title: "物料名称",
                    dataIndex: "inventoryName",
                    align: 'center',
                    width: 80,
                    scopedSlots: {
                        customRender: "inventoryName",
                    },
                },
                {
                    title: "规格型号",
                    dataIndex: "inventorySpecification",
                    align: 'center',
                    width: 80,
                    scopedSlots: {
                        customRender: "inventorySpecification",
                    },
                },
                {
                    title: "生产数量",
                    dataIndex: "baseQuantity",
                    align: 'center',
                    width: 80,
                    scopedSlots: {
                        customRender: "baseQuantity",
                    },
                },
                {
                    title: "完成数量",
                    dataIndex: "cumExecuteQuantity",
                    align: 'center',
                    width: 80,
                    scopedSlots: {
                        customRender: "cumExecuteQuantity",
                    },
                },
                {
                    title: "预计完工时间",
                    dataIndex: "expectFinishDate",
                    align: 'center',
                    width: 80,
                    scopedSlots: {
                        customRender: "expectFinishDate",
                    },
                },
            ],
            columnCheckMaxData: [],
            columnCheckMin: [
                // {
                //   title: "派工单号",
                //   dataIndex: "productionDispatchCode",
                //   align: 'center',
                // },
                // {
                //     title: "工人姓名",
                //     dataIndex: "workerName",
                //     align: 'center',
                //     width: 80,
                //     fixed: 'left',
                // },
                {
                    title: "工序名称",
                    dataIndex: "procedureName",
                    align: 'center',
                    width: 80,
                },
                //  {
                //     title: "班组",
                //     dataIndex: "teamName",
                //     align: 'center',
                //     width: 80,
                // },
                // {
                //     title: "生产车间",
                //     dataIndex: "officeName",
                //     align: 'center',
                //     width: 80,
                // },
                {
                    title: "工序标识",
                    dataIndex: "workFlag",
                    align: 'center',
                    width: 80,
                    customRender: (text, row, index) => {
                        switch (text) {
                            case 1: return "首工序";
                            case 2: return "尾工序";
                            case 3: return "中间工序"
                        }
                    }
                },
                {
                    title: "生产设备",
                    dataIndex: "equipmentName",
                    align: 'center',
                    width: 80,
                },
                {
                    title: "累计合格数量",
                    dataIndex: "cumQualifiedQuantity",
                    align: 'center',
                    width: 100,
                },
                {
                    title: "累计返工数量",
                    dataIndex: "cumReworkQuantity",
                    align: 'center',
                    width: 100,
                },
                {
                    title: "累计不合格数量",
                    dataIndex: "cumUnqualifiedQuantity",
                    align: 'center',
                    width: 100,
                },
                {
                    title: "累计报废数量",
                    dataIndex: "cumScrapQuantity",
                    align: 'center',
                    width: 100,
                },
                // {
                //     title: "状态",
                //     dataIndex: "status",
                //     align: 'center',
                //     width: 80,
                //     customRender: (text, row, index) => {
                //         let { status } = row;
                //         if (status == 0) {
                //             return '加工中'
                //         } else if (status == 10) {
                //             return '完工'
                //         }
                //     }
                // },
            ],
            columnCheckMinData: [],
            //加工单明细表 表格点击监听
            customRowMax: (record, index) => {
                return {
                    on: {
                        click: () => {
                            console.log("加工单明细表", record, index, this.JsonList2)
                            this.maxClickId = record.id;
                        }
                    }
                }
            },
            rowClassMax: (record, index) => {
                return this.maxClickId == record.id ? "hoverRowCard" : "";
            },
            selectedRowMaxKeys: [],
            selectedRowMaxRows: [],
            selectedRowMinKeys: [],
            selectedRowMinRows: [],
        };
    },
    created () {
        //this.getIdByData();//获取最新一条数据
    },
    methods: {
        //新增预测单
        newForecast () {
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(1);
        },
        //保存
        submit (requestData) {
            saveReport(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.editMask = true;
                    this.isSaveRun = true;
                    // if (!this.orderId) {
                        this.getIdByData(); //获取最新一条数据
                    // }
                } else {
                    this.$message.error(response.message);
                    this.isSaveRun = true;
                }
            }).catch((e) => {
                this.isSaveRun = true;
            })
        },
        //单据提交
        submitOrder (type) {
            let data = {
                id: this.orderId,
                status: type,//状态 -1:撤回提交,0:提交
            }
            console.log(this.orderId);
            if (!this.orderId) {
                this.$message.warning('该单据未保存不需要提交');
                return;
            }
            if (this.voucherState == -1 && type == -1) {
                this.$message.warning('该单据未提交无需撤回提交');
                return;
            }
            submitOrder(data).then(res => {
                if (res.code === 200) {
                    if (type == 0) {
                        this.$message.success('提交成功');
                    } else {
                        this.$message.success('撤回提交成功');
                    }
                    this.getIdByData();
                }
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            exameReport(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        remove (postData) {
            deleteReport(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.voucherState = 0;
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //获取单据编号
        getCode () {
            getCodeReport().then((res) => {
                if (res.code == 200) {
                    console.log(res);
                    this.receiptNumber = res.message;
                    console.log(this.orderHeaderData)
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'voucherCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        choiceProduct () {
            this.visibleProcessing = true;
            this.getProduct();
        },
        cancelProcessing () {
            this.visibleProcessing = false;
            this.selectedRowMaxKeys = [];
            this.selectedRowMaxRows = [];
            this.selectedRowMinKeys = [];
            this.selectedRowMinRows = [];
        },
        getProduct () {
            //选择加工产品
            getUnFinishProductionWorkVo({}).then(res => {
                if (res.code == 200) {
                    console.log("获取数据:", res);
                    let maxData = res.data.unFinishProductionWorkDetailSimpleVoList;
                    let minData = res.data.unFinishProductionWorkProcedureVoList;
                    maxData.forEach(item => {
                        item.key = item.id;
                    });
                    minData.forEach(item => {
                        item.key = item.productionWorkProcedureDetailId;
                    });
                    this.columnCheckMaxData = maxData;
                    this.columnCheckMinData = minData;
                }
            });
        },
        onSelectChangeMax (keys, rows) {
            this.selectedRowMaxKeys = keys;
            this.selectedRowMaxRows = rows;
            console.log(keys, rows)

            this.selectedRowMinKeys = [];
            this.selectedRowMinRows = [];

            this.columnCheckMinData.forEach(item => {
                keys.forEach(key => {
                    if (key == item.productionWorkDetailId) {
                        this.selectedRowMinKeys.push(item.key);
                        this.selectedRowMinRows.push(item);
                    }
                });
            });
        },
        onSelectChangeMin (keys, rows) {
            this.selectedRowMinKeys = keys;
            this.selectedRowMinRows = rows;

            this.selectedRowMaxKeys = [];
            this.selectedRowMaxRows = [];
            console.log(keys, rows);
            this.columnCheckMaxData.forEach(item => {
                rows.forEach(key => {
                    if (key.productionWorkDetailId == item.id) {
                        this.selectedRowMaxKeys.push(item.id);
                        this.selectedRowMaxRows.push(item);
                    }
                });
            });
        },
        //通过工艺明细ID 查询 工艺明细 以及 对应最新的工价
        listProcessRouteAndPriceDetailVoByRouteDetailIds(data,ids){
            // if(!data || !data.length || !ids || !ids.length)return;
            listProcessRouteAndPriceDetailVoByRouteDetailIds(ids).then(res => {
                let wagesTypeDesign = this.dynamicFormDataMap.get("wagesType_明细");
                if(res.code == 200){
                    let priceMap = new Map();
                    res.data.forEach(item=>priceMap.set(item.processRouteDetailId,item));
                    data.forEach(detail=>{
                        let priceItem = priceMap.get(detail.processRouteDetailId);
                        if(!priceItem)return;
                        detail.qualifiedPrice = priceItem.lastQualifiedPrice || priceItem.qualifiedPrice || 0.00;
                        detail.reworkPrice = priceItem.lastReworkPrice || priceItem.reworkPrice || 0.00;
                        detail.unqualifiedPrice = priceItem.lastUnqualifiedPrice || priceItem.unqualifiedPrice || 0.00;
                        detail.scrapPrice = priceItem.lastScrapPrice || priceItem.scrapPrice || 0.00;
                        detail.workHourPrice = priceItem.lastWorkHourPrice || priceItem.workHourPrice || 0.00;
                        detail.procedureOrder = priceItem.procedureOrder;
                        if(wagesTypeDesign && wagesTypeDesign.columnType == '下拉选择'){
                            let label = this.handleDownChoice(priceItem.wagesType, wagesTypeDesign.val);
                            detail["wagesType"] = label;
                            detail["wagesType" + 'Id'] = priceItem.wagesType;
                        }else{
                            detail.wagesType = priceItem.wagesType;
                        }
                        // let { procedureFlag,procedureId,procedureName,procedureCode,procedureOrder,procedurePriceDetailId,processRouteDetailId } = priceItem;
                        // Object.assign(detail,{procedureFlag,procedureId,procedureName,procedureCode,procedureOrder,procedurePriceDetailId,processRouteDetailId});
                    });
                    this.reload();
                    console.log('------------ 选择工序明细后，查询工序最新价格',this.dataSource);
               }
            });
        },
        //选单 工序汇报
        addClick () {
            if (this.selectedRowMaxRows.length < 1) {
                this.$message.warning('请选择加工产品');
                return;
            }
            // todo 
            this.orderId = null;
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.dynamicFormData.forEach(item=> {
                delete item.value;
                if (item.columnType == '日期' ) {
                    this.$set(item, 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'));
                    console.log("------ 工序汇报 日期设置默认值 ------",item);
                }else if(item.code == 'officeId'){
                    this.$set(item, 'valueId', this.selectedRowMaxRows[0].officeId);
                    this.$set(item, 'valueName', this.selectedRowMaxRows[0].officeName);
                    this.$set(item, 'value', this.selectedRowMaxRows[0].officeName);
                    console.log("------ 工序汇报 生产车间 重新赋值 ------",item);
                }else if (item.code == 'voucherState'){
                    this.$set(item, 'value',-1);
                }

            });
            let map = new Map();
            let data = [];
            this.selectedRowMaxRows.forEach(item => {
                item.id = null;
                map.set(item.key, item);
            });
            let processRouteDetailIdsSet =  new Set();
            let wagesTypeDesign = this.dynamicFormDataMap.get("wagesType_明细");
            this.selectedRowMinRows.forEach((item, index) => {
                processRouteDetailIdsSet.add(item.processRouteDetailId);
                let wagesType = item.wagesType;
                console.log("----wagesType---",wagesType);
                data[index] = Object.assign(item, map.get(item.productionWorkDetailId))
                data[index].procedureFlag = item.workFlag;
                data[index].procedureOrder = item.procedureOrder
                data[index].productionWorkMainCode = item.productionWorkCode;
                if(wagesTypeDesign && wagesTypeDesign.columnType == '下拉选择'){
                    let label = this.handleDownChoice(wagesType, wagesTypeDesign.val);
                    data[index].wagesType = label;
                    data[index].wagesTypeId = wagesType;
                }else{
                    data[index].wagesType = wagesType;
                }
                delete item.id;
                //  item.id = null;
            });
            const newData = [...data];
            console.log('-- 数据准备 --',newData,processRouteDetailIdsSet);
            this.listProcessRouteAndPriceDetailVoByRouteDetailIds(newData,processRouteDetailIdsSet);
            // data.forEach(item => {
            //     item.id = null;
            // });
            this.dataSource = data;
            console.log("--------- 选择需要汇报的工序后--：",this.dataSource)
            //补足表格
            if (this.dataSource.length < this.dataSourceNumber) {
                for (let i = this.dataSource.length; i < this.dataSourceNumber; i++) {
                    let array = {
                        number: i + 1,
                    };
                    this.dataSource.push(array);
                }
                this.addTotal();//添加合计
            } else {
                for (let i = 0; i < 2; i++) {
                    let array = {
                        number: i + 1,
                    };
                    this.dataSource.push(array);
                }
                this.addTotal();//添加合计
            }
            this.cancelProcessing();//关闭弹窗
            this.reload();
            // this.isHeaderShow = false;
            // this.$nextTick(()=>{
            //     this.orderHeaderData = oldOrderHeaderData
            //     this.isHeaderShow = true;
            //     this.getCode();
            //     ;
            // });
            this.getCode();

        }
    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .hoverRowCard {
        background-color: rgba(24, 144, 255, 0.2);
        td {
            color: #222;
        }
    }
</style>